package document

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// GetTemplatesHandler 获取公文模板列表
func GetTemplatesHandler(c *gin.Context) {
	var req GetTemplatesRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误: " + err.Error(),
		})
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 || req.PageSize > 100 {
		req.PageSize = 10
	}

	service := NewDocumentService()
	templates, err := service.GetTemplates()
	if err != nil {
		logrus.Errorf("获取模板列表失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "获取模板列表失败",
		})
		return
	}

	// 分页处理
	total := len(templates)
	start := (req.Page - 1) * req.PageSize
	end := start + req.PageSize
	if start > total {
		start = total
	}
	if end > total {
		end = total
	}

	response := GetTemplatesResponse{
		Success:   true,
		Templates: templates[start:end],
		Total:     total,
		Page:      req.Page,
		PageSize:  req.PageSize,
	}

	c.JSON(http.StatusOK, response)
}

// GenerateDocumentHandler 生成公文
func GenerateDocumentHandler(c *gin.Context) {
	var req GenerateDocumentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误: " + err.Error(),
		})
		return
	}

	service := NewDocumentService()
	response, err := service.GenerateDocument(&req)
	if err != nil {
		logrus.Errorf("生成公文失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "生成公文失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, response)
}

// GenerateDocumentFormHandler 表单方式生成公文
func GenerateDocumentFormHandler(c *gin.Context) {
	var req GenerateDocumentRequest
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "参数错误: " + err.Error(),
		})
		return
	}

	service := NewDocumentService()
	response, err := service.GenerateDocument(&req)
	if err != nil {
		logrus.Errorf("生成公文失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "生成公文失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, response)
}

// HealthHandler 健康检查
func HealthHandler(c *gin.Context) {
	response := HealthResponse{
		Status:  "ok",
		Message: "公文生成系统运行正常",
		Time:    time.Now().Format("2006-01-02 15:04:05"),
	}
	c.JSON(http.StatusOK, response)
}
